﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

using SManaApi.Services;

using SManaModel;
using SManaModel.dtos;
using SManaModel.utils;
using SManaModel.entities;
using SManaModel.models;

using System.Linq.Expressions;

namespace SManaApi.Controllers
{
    /// <summary>
    /// 控制器父类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    [Route("/api/[controller]")]
    [ApiController]
    [Authorize]
    public class MasterController<T> : ControllerBase
    {
        protected readonly ILogger<T>? _logger;
        protected readonly MyDbContext? _dbContext;

        public MasterController(ILogger<T> logger, MyDbContext dbContext)
        {
            _logger = logger;
            _dbContext = dbContext;
        }


        protected virtual ApiResult general_get<TReq, TEntity, TKey, TDto>(SearchPageDto generalPageDto, IBaseService<TEntity> baseService, Expression<Func<TEntity, TKey>> orderbyExpression) where TEntity : class
        {
            if (generalPageDto is null)
            {
                return ApiResult.FailOfParams();
            }

            var servicePageComponent = ServicePageComponent<TEntity, TKey>.Create(
                PageComponent.Create(generalPageDto),
                orderbyExpression,
                entity => true,
                false);
            List<TEntity>? list = baseService.GetEntitiesByPage(servicePageComponent)?.ToList();
            IList<TDto>? out_list = list?.ConvertTo<TDto>();
            var count = baseService.GetCount();

            return ApiResult.Ok(data: new { list = out_list, totalNum = count });
        }

        protected virtual ApiResult general_add<TDto, TEntity>(TDto dto, IBaseService<TEntity> baseService, Func<TDto, TEntity>? backFunc = null) where TEntity : class
        {
            if (dto is null)
            {
                return ApiResult.FailOfParams();
            }

            var entity = backFunc == null ? dto.ConvertTo<TEntity>() : backFunc(dto);
            var n = baseService.AddEntity(entity);
            return ApiResult.Judge(n);
        }

        [Obsolete("此方法没有用, 走不通")]
        protected virtual ApiResult general_delete<TEntity>(string? id, IBaseService<TEntity> baseService, Func<TEntity, int, bool> whereExpression) where TEntity : class
        {
            if (id is null)
            {
                return ApiResult.FailOfParams();
            }

            var ids = id.Split(',', StringSplitOptions.RemoveEmptyEntries);
            foreach (var id_str in ids)
            {
                if (int.TryParse(id_str, out var i))
                {
                    baseService.DeleteEntity(entity => whereExpression(entity, i));
                }
            }
            return ApiResult.Ok();
        }

        protected virtual ApiResult general_update<TReq, TEntity>(TReq dto, IBaseService<TEntity> baseService) where TEntity : class
        {
            if (dto is null)
            {
                return ApiResult.FailOfParams();
            }
            var entity = dto.ConvertTo<TEntity>();
            var n = baseService.UpdateEntity(entity);
            return ApiResult.Judge(n);
        }
    }
}
